package lulu.taglib.basic;


import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * Created by IntelliJ IDEA.
 * User: Ivan
 * Date: 2010-6-14
 * Time: 12:51:52
 */
public class Label extends TagSupport {

    private String name = null;
    private String styleClass = null;
    private String style = null;

    public void setName(String name) {
        this.name = name;
    }
    
    public void setStyleClass(String styleClass){
    	    this.styleClass = styleClass;
    }
    
    public void setStyle(String style){
    	    this.style = style;
    }

    public int doStartTag() throws JspException {
        try {
            JspWriter out = pageContext.getOut();
            out.print(getValueByLanguage());
        } catch (Exception e) {
            throw new JspException(e);
        }

        return EVAL_PAGE;
    }

    private String getValueByLanguage() {
        String languagecode = pageContext.getServletContext().getInitParameter("languagecode");

        String[] t = languagecode.split("_");

        if(t.length != 2){
            t = new String[]{"zh","CN"};
        }

        Locale locale = new Locale(t[0], t[1]);
        ResourceBundle messages = ResourceBundle.getBundle("messages", locale);
        String value = messages.getString(name);
        
        return warp(value);
    }
    
    private String warp(String str){
    	    String temp1 = "";
    	    String temp2 = "";
    	    if(styleClass != null){
    	    	    temp1 = " class=\"" + styleClass + "\"";
    	    }
    	    if(style != null){
    	    	    temp2 = " style=\"" + style + "\"";
    	    }
    	    
    	    if(temp1.trim().equals("") && temp2.trim().equals("")){
    	    	    return filter(str);
    	    }else{
    	            return filter("<span" + temp1 + temp2 + ">" + str + "</span>");
    	    }
    }

    private String filter(String str) {
        return str;
    }
}
